/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "set_key_event_serializer.h"
#include <string>
#include <map>
#include "cJSON.h"
#include "cjson_check.h"

namespace OHOS {
namespace EDM {

bool SetKeyEventSerializer::Deserialize(const std::string &jsonString, std::map<int, int> &dataObj)
{
    if (jsonString.empty()) {
        return true;
    }

    cJSON *root = cJSON_Parse(jsonString.c_str());
    if (root == nullptr) {
        EDMLOGE("Failed to parse JSON string.");
        return false;
    }

    if (!cJSON_IsObject(root)) {
        EDMLOGE("JSON is not an object.");
        cJSON_Delete(root);
        return false;
    }

    cJSON *item = nullptr;
    cJSON_ArrayForEach(item, root) {
        if (!cJSON_IsNumber(item)) {
            EDMLOGE("item is not a number.");
            cJSON_Delete(root);
            return false;
        }
        int key = std::stoi(item->string);
        dataObj[key] = item->valueint;
    }

    cJSON_Delete(root);
    return true;
}

bool SetKeyEventSerializer::Serialize(const std::map<int, int> &dataObj, std::string &jsonString)
{
    cJSON *root = nullptr;
    CJSON_CREATE_OBJECT_AND_CHECK(root, false);

    for (const auto &item : dataObj) {
        std::string keyStr = std::to_string(item.first);
        cJSON *valueItem = cJSON_CreateNumber(item.second);
        if (valueItem == nullptr) {
            cJSON_Delete(root);
            return false;
        }
        if (cJSON_AddItemToObject(root, keyStr.c_str(), valueItem) == 0) {
            cJSON_Delete(root);
            return false;
        }
    }

    char *jsonStr = cJSON_Print(root);
    if (jsonStr == nullptr) {
        cJSON_Delete(root);
        return false;
    }

    jsonString = jsonStr;
    cJSON_free(jsonStr);
    cJSON_Delete(root);
    return true;
}
 
} // namespace EDM
} // namespace OHOS